<?php

$port = 9502;
// var_dump($argv);
if(empty($argv[1]) == false){
    $port = intval($argv[1]);
}
$client = new swoole_client(SWOOLE_SOCK_TCP);

if (!$client->connect('127.0.0.1', 9502, -1))
{ 
    exit("connect failed. Error: {$client->errCode}\n");
}
$client->on("error", function($cli){
    echo "Connect failed======\n";
});
$client->on("close", function($cli){
    echo "Connection close\n";
});


swoole_timer_tick(3000, function($id) {
    global $client;
    global $port;
    $data = array('host'=>'127.0.0.1', 'port'=>$port, 'time'=>time(), 'datetime'=>date("Y-m-d H:i:s"));
//     $data = array($data);
    echo "client->errCode======" . $client->errCode." client->isConnected==={$client->isConnected()}\n";
    if($client->errCode > 0){
        $client->close();
        $client->errCode = 0;
    }
    if($client->isConnected() == false){  // $client->isConnected() == false && 
        echo "connect retry \n";
        $client->connect('127.0.0.1', 9502, -1);
    }
    else{
        $send_data = json_encode($data)."\r\n";
        try{
            $client->send($send_data);
        }
        catch(Exception $ex){
            $client->close();
            echo "send error======" . $ex->getTrace()."\n";
        }
        $rec_data = $client->recv();
        echo $rec_data;
    }
   
});
// $client->close();